<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2020/11/30
 * Time: 11:46 AM
 */
namespace App\Api\Controllers\DongGuan;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\Config\TfConfigController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\HkrtStore;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\TfStore;
use App\Models\UserRate;
use App\Models\UserWalletDetail;
use App\Services\Pay\PayService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use MyBank\Tools;

class NotifyController extends BaseController
{
    //海科融通 支付 回调
    public function pay_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('海科融通支付回调原始数据');
            Log::info($data);
//            $data = array (
//                'merch_no' => '88888888',
//                'card_type' => '[{"amount":"0.01","fund_channel":"ALIPAYACCOUNT"}]',
//                'channel_trade_no' => '010720052318031308516MC',
//                'trade_type' => 'ALI',
//                'trade_status' => '1',
//                'out_trade_no' => 'aliscan20200523175704657510433',
//                'trade_no' => 'AL200523180326867181166148',
//                'total_amount' => '0.01',
//                'fee' => '0.00',
//                'sn' => NULL,
//                'remark' => NULL,
//                'attach' => '{"msg":"Success","gmt_payment":"2020-05-18 15:44:35","code":"10000","buyer_user_id":"2088902194581584","invoice_amount":"0.01","fund_bill_list":[{"amount":"0.01","fund_channel":"ALIPAYACCOUNT"}],"out_trade_no":"010220051815441306245MC","total_amount":"0.01","trade_no":"2020051822001481581447791185","receipt_amount":"0.01","buyer_logon_id":"819***@qq.com","point_amount":"0.00","buyer_pay_amount":"0.01"}',
//                'trade_channel_end_time' => '2020-05-18 15:44:35',
//                'userid' => '2088902194581584',
//                'alipay_no' => '2020051822001481581447791185',
//                'sign' => '024E6156BD67D350A6C890C1E0531D47',
//            );
//            $data = array ( //微收银-微信-被扫
//                'merch_no' => '88888888',
//                'card_type' => '"OTHERS"',
//                'channel_trade_no' => '011020052610471308713MC',
//                'trade_type' => 'WX',
//                'trade_status' => '1',
//                'out_trade_no' => 'wxscan20200526104726600139107',
//                'trade_no' => 'WX200526104726722251348214',
//                'total_amount' => '0.01',
//                'fee' => '0.00',
//                'sn' => NULL,
//                'remark' => NULL,
//                'attach' => '{"transaction_id":"4200000525202005268471433114","nonce_str":"HTt5vosRVQdYmPY54al0h4MkThdHKNAY","bank_type":"OTHERS","openid":"oUpF8uJXVGy4NoXBSWyolM2Q_2s0","fee_type":"CNY","mch_id":"1900008751","sub_mch_id":"315211682","cash_fee":"1","out_trade_no":"011020052610471308713MC","cash_fee_type":"CNY","coupon_fee":"0","appid":"wx2421b1c4370ec43b","total_fee":"1","settlement_total_fee":"1","trade_type":"MICROPAY","result_code":"SUCCESS","time_end":"20200526104728","return_code":"SUCCESS"}',
//                'trade_channel_end_time' => '2020-05-26 10:47:28',
//                'appid' => NULL,
//                'openid' => NULL,
//                'weixin_no' => '4200000525202005268471433114',
//                'sign' => '828D6CEA9F5C93CA4726BCF8F1CC3F0C',
//            );

            if (isset($data['trade_no']) || isset($data['out_trade_no'])) {
                $trade_no = $data['trade_no'];
                $out_trade_no = $data['out_trade_no'];

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                    if (!$order) $order = DB::table($table)->where('trade_no', $trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                    if (!$order) $order = Order::where('trade_no', $trade_no)->first();
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == '2') {
                        if (isset($data['attach']) && !empty($data['attach'])) {
                            $return_attach = json_decode($data['attach'], true);
                            if ($return_attach['msg'] == 'Success') {
                                $pay_time = $return_attach['gmt_payment']; //
                                $buyer_user_id = $return_attach['buyer_user_id']; //
                                $buyer_pay_amount = $return_attach['buyer_pay_amount']; //
                                $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                            }
                            if (($data['card_type'] == 'OTHERS') && ($return_attach['result_code'] == 'SUCCESS')) {
                                $pay_time = $data['trade_channel_end_time'];
                                $buyer_user_id = $return_attach['openid'];
                                $other_no = $return_attach['out_trade_no'];
                            }
                        }
//                        $buyer_pay_amount = $data['total_amount']; //订单总金额，以元为单位
//                        $buyer_id = $data['userid']; //用户id
                        $in_data = [
                            'status' => '1',
                            'pay_status' => 1,
                            'pay_status_desc' => '支付成功',
                            'trade_no' => $trade_no,
//                            'pay_time' => $pay_time,
//                            'buyer_id' => $buyer_user_id,
//                            'buyer_pay_amount' => $buyer_pay_amount,
                        ];
                        if(isset($pay_time) && !empty($pay_time)) $in_data['pay_time'] = $pay_time;
                        if(isset($buyer_user_id) && !empty($buyer_user_id)) $in_data['buyer_id'] = $buyer_user_id;
                        if(isset($buyer_pay_amount) && !empty($buyer_pay_amount)) $in_data['buyer_pay_amount'] = $buyer_pay_amount;
                        if(isset($other_no) && !empty($other_no)) $in_data['other_no'] = $other_no;
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '22000', //返佣来源
                                'source_desc' => '海科融通', //返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $order->fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
//                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            if(isset($pay_time) && !empty($pay_time)) $data['pay_time'] = $pay_time;
                            PaySuccessAction::action($data);
                        }
                    } else {
                        //系统订单已经成功了
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $exception) {
            Log::info('海科融通支付异步报错');
            Log::info($exception->getMessage());
        }
    }


    //海科融通 退款 回调
    public function refund_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('海科融通退款回调原始数据');
            Log::info($data);
//            $data =   array (
//                'merch_no' => '88888888',
//                'card_type' => '""',
//                'channel_trade_no' => '011220052814321309015MC',
//                'refund_no' => 'AL200528143212041477008596',
//                'out_refund_no' => 'aliscan202005281401209433493018738',
//                'refund_amount' => '0.01',
//                'refund_type' => 'ALI',
//                'refund_status' => '1',
//                'out_trade_no' => 'aliscan20200528140120943349301',
//                'trade_no' => 'AL200528140121249411945272',
//                'total_amount' => '0.01',
//                'total_refund_amount' => '0.01',
//                'sn' => NULL,
//                'remark' => NULL,
//                'sign' => '177888F014C33C921FE0A81C3C1188D6',
//            );

            if (isset($data['refund_no']) || isset($data['out_refund_no'])) {
                $refund_no = $data['refund_no']; //SaaS平台的退款订单编号
                $out_trade_no = $data['out_refund_no']; //服务商退款订单号
                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'orders_' . $day;

                $out_trade_no = substr($out_trade_no , 0, strlen($out_trade_no)-4);

                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order && $order->pay_status == '1') {
                    if ($data['refund_status'] == '1') {
                        $refund_amount = $data['refund_amount']; //本次退款金额,以元为单位
                        $update_data = [
                            'status' => '6',
                            'pay_status' => '6',
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $order->refund_amount + $refund_amount,
                            'fee_amount' => 0,
                        ];
                        if (Schema::hasTable($table)) {
                            DB::table($table)
                                ->where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        } else {
                            Order::where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        }
                        if (Schema::hasTable('order_items')) {
                            OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
                        }

                        RefundOrder::create([
                            'ways_source' => $order->ways_source,
                            'type' => $order->ways_type,
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $refund_no, //SaaS平台的退款订单编号
                            'store_id' => $order->store_id,
                            'merchant_id' => $order->merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->other_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$refund_no, //平台退款单号
                        ]);
                        //返佣去掉
                        UserWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                        MerchantWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                    }
                }
            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $exception) {
            Log::info('海科融通退款异步报错');
            Log::info($exception->getMessage());
        }
    }


    //海科融通 商户入网申请 回调
    public function merchant_apply_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('海科融通-商户入网申请-回调原始数据');
            Log::info($data);

            //TODO:更改进件状态
            //3的状态是系统审核通过   系统审核过了之后就可以报备业务并且交易，但是后续人工会有一个复审
//            $store_info = Store::where()->first();
//            if (!$store_info) {
//                Log::info('海科融通-商户入网申请-回调-门店不存在');
//            }

//            $hkrt_store = HkrtStore::where()->first();
//            if ($hkrt_store->status != '1') {
//                $hkrt_store->update([
//                    'merch_no' => '',
//                    'status' => '1',
//                ]);
//                $hkrt_store->save();
//            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $exception) {
            Log::info('海科融通-商户入网申请-回调异步报错');
            Log::info($exception->getMessage());
        }
    }


    //海科融通 商户结算卡变更 回调
    public function merchant_bank_info_modify_notify_url(Request $request)
    {
        try {
            $data = $request->all();
            Log::info('海科融通-商户结算卡变更-回调-原始数据');
            Log::info($data);

            //TODO:更改结算卡信息
//            $store_info = Store::where()->first();
//            if (!$store_info) {
//                Log::info('海科融通-商户入网申请-回调-门店不存在');
//            }

            return json_encode([
                'code' => 'success',
                'msg' => "成功",
            ]);
        } catch (\Exception $exception) {
            Log::info('海科融通-商户结算卡变更-回调-异步报错');
            Log::info($exception->getMessage());
        }
    }


}
